﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TaskManager.Data;
using System.Web.Script.Serialization;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace TaskManager.Views
{
    public partial class DeveloperPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.RequestType != "POST")
            {
                using (IUnityContainer container = new UnityContainer())
                {
                    container.LoadConfiguration();
                    ISprintRepository sprintRepository = container.Resolve<ISprintRepository>();
                    Developer developer = sprintRepository.GetDevelopers().Where(d => d.DeveloperId == Convert.ToInt32(Request.QueryString["id"])).First();
                    this.DeveloperId.Value = developer.DeveloperId.ToString();
                    this.FirstName.Text = developer.FirstName;
                    this.LastName.Text = developer.LastName;
                    this.Title.Text = developer.Title;
                }
            }
        }

        [System.Web.Services.WebMethod]
        public static object GetDeveloperTasks(int id)
        {
            IList<Task> tasks = null;

            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                ISprintRepository sprintRepository = container.Resolve<ISprintRepository>();
                Developer developer = sprintRepository.GetDevelopers().Where(d => d.DeveloperId == id).FirstOrDefault();
                tasks = developer.GetTasks();
            }
            return tasks.Select(t => new
            {
                TaskId = t.TaskId,
                SprintId = t.SprintId,
                TypeOfTask = t.TypeOfTask,
                EstimatedHours = t.EstimatedHours,
                Description = t.Description,
                AssignedToId = t.AssignedToId,
                CompletedDate = t.CompletedDate
            });
        }

        [System.Web.Services.WebMethod]
        public static void UpdateDeveloper(string json)
        {
            Developer developer = new JavaScriptSerializer().Deserialize(json, typeof(Developer)) as Developer;

            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                ISprintRepository sprintRepository = container.Resolve<ISprintRepository>();
                sprintRepository.SaveDeveloper(developer);
            }
        }
    }
}